<script setup>
import {
  findAllProjectByGroupIdApi,
  findAllProjectTaskApi,
  findMemberTaskParticipationApi,
  findProjectDetailsByProjectIdApi,
  getAllGroupApi
} from "@/apis/taskManagement"
import { getCurrentRouteQuery } from "@/utils/routerUtils"
import { ref, watch } from "vue"
import avatarName from '@/components/avatarName'
import router from "@/router"
import * as echarts from "echarts"
import { Search as IconSearch } from '@element-plus/icons-vue'
import { dayjs } from "element-plus"

const query = getCurrentRouteQuery()
const filePrefix = process.env.VUE_APP_BASE_URL
const groups = ref([])
const breadcrumb = ref('')
const projectPanelLoading = ref(true)
const projectList = ref([])
const projectListOptions = ref([])
const memberTaskParticipationLoading = ref(true)
const memberTaskParticipation = ref([])
const tableData = ref([])
const tableLoading = ref(true)
const projectDetails = ref({
  owner: {},
  coverImgPath: ''
})
const projectSearch = ref()
const isFirstProjectSearch = ref(true)
const projectSearchLoading = ref(true)
const taskSearch = ref({})

getAllGroupApi().then(({data}) => {
  groups.value = data
  breadcrumb.value = data.find(group => group.id + '' === getCurrentRouteQuery().groupId).gName
})

findAllProjectByGroupIdApi({groupId: query.groupId}).then(({data}) => {
  projectList.value = data || []
  projectListOptions.value = data || []
  projectSearchLoading.value = false
  projectPanelLoading.value = false
  if (projectList.value.length > 0) {
    findProjectDetailsByProjectIdApi({id: query.projectId || projectList.value[0].id}).then(({data}) => {
      projectDetails.value = data
      projectSearch.value = projectDetails.value.id
      router.replace(`/system/taskManagement/overview?groupId=${ query.groupId }&projectId=${ query.projectId || projectDetails.value.id }`)
      initChart()
    })
    findAllProjectTask(query.projectId || projectList.value[0].id)
  }
})

const findAllProjectTask = (projectId) => {
  tableLoading.value = true
  findAllProjectTaskApi({
    groupId: query.groupId,
    id: projectId || getCurrentRouteQuery().projectId, ...taskSearch.value
  }).then(({data}) => {
    tableData.value = data.dataList || []
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    tableLoading.value = false
  })
}


const onProjectRemoteMethod = (name) => {
  projectListOptions.value = []
  projectList.value.forEach(p => {
    if (p.name.includes(name)) {
      projectListOptions.value.push(p)
    }
  })
}

const onTaskTableSearch = () => {
  findAllProjectTask()
}

const initChart = () => {
  const myChart = echarts.init(document.getElementById('echarts-task-group'))
  findMemberTaskParticipationApi({groupId: query.groupId, projectId: projectDetails.value.id}).then(res => {
    const data = res.data || []
    memberTaskParticipationLoading.value = false
    myChart.setOption({
      title: {
        text: '组内成员参与任务情况'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        data: data.map(d => d.name),
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          show: true,
          interval: 0,
          rotate: -60,
          inside: false,
          margin: 6
        }
      },
      yAxis: {
        minInterval: 1
      },
      series: [
        {
          name: '数量',
          type: 'bar',
          data: data.map(d => d.number),
          itemStyle: {
            borderRadius: [4, 4, 0, 0] //（顺时针左上，右上，右下，左下）
          }
        }
      ]
    })
  })
}

const onGoTo = (row) => {
  console.log(row)
  router.push(`/system/projectManagement/projectTask/projectTaskDetails?taskId=${ row.id }&groupId=${ query.groupId }&name=${ row.name }&projectId=${ row.project.id }`)
}

watch(projectSearch, (n, o) => {
  if (isFirstProjectSearch.value) {
    isFirstProjectSearch.value = false
    return
  }
  taskSearch.value = {}
  findProjectDetailsByProjectIdApi({id: n}).then(({data}) => {
    projectDetails.value = data
    projectSearch.value = n
    router.replace(`/system/taskManagement/overview?groupId=${ query.groupId }&projectId=${ projectDetails.value.id }`)
    initChart()
  })
  findAllProjectTask(n)
})

</script>

<template>
  <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 24px">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>{{ breadcrumb }}</el-breadcrumb-item>
    <el-breadcrumb-item>任务总览</el-breadcrumb-item>
  </el-breadcrumb>
  <el-container>
    <el-aside width="380px">
      <el-card shadow="hover" style="margin-bottom: 12px;" v-loading="projectPanelLoading">
        <el-form label-position="left" label-width="auto">
          <el-form-item label="项目总数">
            <div>{{ projectList.length }}</div>
          </el-form-item>
          <el-form-item label="项目选择">
            <el-select
                v-model="projectSearch"
                :remote-method="onProjectRemoteMethod"
                placeholder="输入项目名搜索"
                :loading="projectSearchLoading"
                style="width: 310px"
                clearable
                filterable
                remote
            >
              <el-option
                  v-for="project in projectListOptions"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"
              >
                <span style="float: left">{{ project.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <img class="project-image" :src="filePrefix + projectDetails.coverImgPath" alt="">
          </el-form-item>
          <el-form-item>
            <div>{{ projectDetails.name }}</div>
          </el-form-item>
          <el-form-item label="项目负责人">
            <avatar-name
                :url="projectDetails.owner.avatar ? filePrefix + projectDetails.owner.avatar : projectDetails.owner.name"
                :name="projectDetails.owner.name" />
          </el-form-item>
        </el-form>

      </el-card>
      <el-card shadow="hover" v-loading="memberTaskParticipationLoading">
        <div id="echarts-task-group" style="height: 268px;">

        </div>
      </el-card>
    </el-aside>
    <el-main style="padding-top: 0">
      <el-card shadow="hover">
        <el-form inline>
          <div style="display: flex; justify-content: space-between;">
            <div>
              <el-form-item label="任务名">
                <el-input v-model="taskSearch.name" placeholder="输入任务名"></el-input>
              </el-form-item>
              <el-form-item label="任务状态">
                <el-select
                    v-model="taskSearch.status"
                    placeholder="选择任务状态"
                    size="default"
                    style="width: 240px"
                    clearable
                >
                  <el-option label="未开始" :value="0" />
                  <el-option label="进行中" :value="1" />
                  <el-option label="已完成" :value="2" />
                  <el-option label="已逾期" :value="3" />
                </el-select>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="" style="margin-right: 0">
                <el-button type="primary" :icon="IconSearch" @click="onTaskTableSearch">搜索</el-button>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <el-table v-loading="tableLoading" :data="tableData" stripe style="width: 100%; margin-top: 12px;"
                  max-height="580">
          <el-table-column label="任务名" prop="name">
            <template #default="scope">
              <span @click="onGoTo(scope.row)" class="task-name">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="任务创建人" prop="creatorUsername">
            <template #default="scope">
              <avatar-name
                  :url="scope.row.creatorAvatar ? filePrefix + scope.row.creatorAvatar : scope.row.creatorName"
                  :name="scope.row.creatorName" />
            </template>
          </el-table-column>
          <el-table-column label="任务负责人" prop="owner">
            <template #default="scope">
              <avatar-name :url="scope.row.owner.avatar ? filePrefix + scope.row.owner.avatar : scope.row.owner.name"
                           :name="scope.row.owner.name" />
            </template>
          </el-table-column>
          <el-table-column label="任务状态" prop="status">
            <template #default="scope">
              <div v-if="scope.row.status === 0">未开始</div>
              <div v-else-if="scope.row.status === 1">进行中</div>
              <div v-else-if="scope.row.status === 2">已完成</div>
              <div v-else-if="scope.row.status === 3">已逾期</div>
            </template>
          </el-table-column>
          <el-table-column label="参与人" prop="creatorUsername">
            <template #default="scope">
              <el-tag style="margin-right: 4px" type="primary" v-for="p in scope.row.participants" :key="p.id">{{
                  p.name
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建日期" prop="createTime">
            <template #default="scope">
              {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
  </el-container>
</template>

<style scoped lang="less">
.project-image {
  //object-fit: cover;
  width: 100%;
  height: 160px;
  border-radius: 5px;
  object-fit: cover;
  object-position: center
}

.el-form-item {
  margin-bottom: 4px;
}

.task-name {
  cursor: pointer;
}

.task-name:hover {
  color: #409eff;
}

</style>